<?php

namespace backend\controllers;

use Yii;
use backend\models\Document;
use backend\models\DocumentArticle;
use backend\models\DocumentSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;
use yii\web\UploadedFile;
use yii\grid\GridView;
use yii\data\ActiveDataProvider;

/**
 * 
 * DocumentController implements the CRUD actions for Document model.
 */
class DocumentController extends Controller {

    private $model;

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['GET'],
                ],
            ],
        ];
    }

    public function actions() {
        return [
            'upload' => [
                'class' => 'kucha\ueditor\UEditorAction',
                'config' => [
                    "imageUrlPrefix" => "", //图片访问路径前缀
                    "imagePathFormat" => "/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}" //上传保存路径
                ],
            ]
        ];
    }

    public function init() {
        parent::init();

        $this->model = new Document();
    }

    /**
     * Lists all Document models.
     * @return mixed
     */
    public function actionIndex() {
        $searchModel = new DocumentSearch();

        $queryParams = Yii::$app->request->queryParams;
        //过滤表单 只显示 正常的内容
        $queryParams['DocumentSearch'] = array(
            'status' => '1',
        );

        Yii::$app->request->setQueryParams($queryParams);

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

//        $dataProvider = new ActiveDataProvider([ "query" => $query, ]); 
//        $dataProvider->setSort(false);

        return $this->render('index', [
                    'searchModel' => $searchModel,
                    //'model' => $this->find,
                    'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * 
     *  取得 相应的内容列表  返回数组
     * 
     * @array condition  条件
     * @return  array 
     * * */
    public function actionLists($condition = []) {

//      $dataProvider = new ActiveDataProvider([
//            'query' => Document::find(),
//            'pagination' => [
//                'pageSize' => 20,
//            ],
//        ]);
//        echo GridView::widget([
//            'dataProvider' => $dataProvider,
//        ]);
    }

    /**
     * lists all document in recycle bin
     * 
     * @return mixed
     * * */
    public function actionTrash() {

        $searchModel = new DocumentSearch();

        $queryParams = Yii::$app->request->queryParams;
        //过滤表彰 只显示 垃圾站 内容
        $queryParams['DocumentSearch'] = array(
            'status' => '-1',
        );

        Yii::$app->request->setQueryParams($queryParams);

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);


        return $this->render('trash', [
                    'searchModel' => $searchModel,
                    //'model' => $this->find,
                    'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Document model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id) {
        return $this->render('view', [
                    'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Document model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {

        $model = new Document();
        $modelArticle = new DocumentArticle();


        if (Yii::$app->request->isPost) {

            $post = Yii::$app->request->post();

            $post['Document']['create_time'] = strtotime($post['Document']['create_time']);

            Yii::$app->request->setBodyParams($post);

            //开启事务
            $tr = Yii::$app->db->beginTransaction();

            try {
                if ($model->load(Yii::$app->request->post()) && $model->save(false)) {


                    //保存id 后  返回插入的ID
                    $documentID = Yii::$app->db->getLastInsertId();

                    $post = Yii::$app->request->post();

                    $post['DocumentArticle']['id'] = $documentID;

                    Yii::$app->request->setBodyParams($post);

                    if ($modelArticle->load(Yii::$app->request->post()) && $modelArticle->save(false)) {
                        
                        Yii::$app->getSession()->setFlash('success', '创建成功');
                    } else {

                        Yii::$app->getSession()->setFlash('error', '创建失败');
                    }
                } else {
                    Yii::$app->getSession()->setFlash('error', '创建失败');
                }
                //事务提交
                $tr->commit();
                
            } catch (Exception $e) {
                
                 Yii::$app->getSession()->setFlash('error', '创建失败');   
                $tr->rollBack();
            }

            
            return $this->redirect(['document/create']);

        } else {

            //显示表单
            return $this->render('create', [
                        'model' => $model,
                        'modelArticle' => $modelArticle,
                        'categoryTree' => CategoryController::GetCategoryTree(),
            ]);
        }
    }

    /**
     * Updates an existing Document model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id) {
        
        
        $model = $this->findModel($id);
        $modelArtcle = DocumentArticle::findOne($id);
        
        
        if(Yii::$app->request->isPost){
            if ($model->load(Yii::$app->request->post()) && $model->save(false) && $modelArtcle->load(Yii::$app->request->post()) && $modelArtcle->save(false)) {

                Yii::$app->session->setFlash("success","内容修改成功");
            }else{

                Yii::$app->session->setFlash("error","内容修改失败，请检测 数据是否填写正确");
            }
            
         return $this->redirect(['index', 'id' => $model->id]);
         
        }else{
              return $this->render('update', [
                    'model' => $model,
                    'modelArticle' => $modelArtcle,
                    'categoryTree' => CategoryController::GetCategoryTree(),
        ]);
            
            
        }

      
    }

    /**
     * Deletes an existing Document model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id) {
        $this->findModel($id)->delete();
        Yii::$app->getSession()->setFlash("success", "记录已删除");
        return $this->redirect(['trash']);
    }

    /**
     *  删除到垃圾箱
     * @param int $id 内容的标题
     * @param string  $tag="delete"  放到回收站 默认值   $tag="restore"  还原
     * * */
    public function actionToggleTrash() {

        $id = Yii::$app->request->get("id");
        $tag = Yii::$app->request->get("tag");
        $value = '-1';
        $successMes = "成功放入垃圾箱";
        $errorMes = "放入垃圾箱失败";
        if ($tag == "restore") {
            $value = '1';
            $successMes = "还原成功";
            $errorMes = "还原失败";
        }

        if (@intval($id) < 1) {

            Yii::$app->getSession()->setFlash("error", $errorMes);
            return $this->redirect(\yii\helpers\Url::toRoute("/document/index"));
        } else {

            Document::updateAll(array(
                'status' => $value,
                    ), array('id' => $id));


            Yii::$app->getSession()->setFlash("success", $successMes);
        }

        return $this->redirect(\yii\helpers\Url::toRoute("/document/index"));
    }

    /**
     *   批量删除 [放入回收站]
     * @param string ids 文档ID 用 “，” 隔开  如 1,2,3,4....
     * @return mix ajax 无返回值  直接跳转
     * * */
    public function actionBatchTrash() {

        $message = "数据批量删除成功";
        $handleTag = "success";
        $ids = Yii::$app->request->post("ids");

        if (empty($ids)) {
            $handleTag = "error";
            $message = "删除失败 未选定项目";
        }

        //开始删除内容
        $idAarr = array_filter(explode(",", $ids));

        foreach ($idAarr as $v) {

            Yii::$app->db->createCommand("update {{document}} set status='-1' where id=:id")->bindParam("id", $v)->execute();
        }


        Yii::$app->session->setFlash($handleTag, $message);

        return $this->redirect(\yii\helpers\Url::toRoute("/document/index"));
    }

    /**
     *   批量删除   从回收站中删除   数据删除后 将不能恢复
     * @param string ids 文档ID 用 “，” 隔开  如 1,2,3,4....
     * @return mix ajax 无返回值  直接跳转
     * * */
    public function actionBatchDelete() {

        $tag = Yii::$app->request->post("tag") ? Yii::$app->request->post("tag") : "trash";


        $message = $tag == "delete" ? "批量删除数据成功" : "批量记录回收站成功";
        $handleTag = "success";
        $ids = Yii::$app->request->post("ids");

        if (empty($ids)) {
            $handleTag = "error";
            $message = $tag == "delete" ? "批量删除数据失败 未选定项目" : "批量记录回收站失败 未选定项目";
        }

        //开始删除内容
        $idAarr = array_filter(explode(",", $ids));

        foreach ($idAarr as $v) {
            if ($tag == 'delete') {

                Yii::$app->db->createCommand("delete from {{document}} where id=:id")->bindParam("id", $v)->execute();
            } else {
                Yii::$app->db->createCommand("update {{document}} set status='-1' where id=:id")->bindParam("id", $v)->execute();
            }
        }

        Yii::$app->session->setFlash($handleTag, $message);
        $callbackUrl = $tag == "delete" ? \yii\helpers\Url::toRoute("/document/trash") : \yii\helpers\Url::toRoute("/document/index");
        return $this->redirect($callbackUrl);
    }

    /**
     * Finds the Document model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Document the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        if (($model = Document::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }

    /**
     *  上传图片
     * @return  json 以json返回
     *      */
    public function actionUploadimage() {

        //关闭 _CSRF 验证
        //$this->enableCsrfValidation = false;
//        Yii::$app->request->enableCsrfValidation = false;
        //Yii::$app->response->format=Response::FORMAT_JSON;


        $targetFolder = Yii::$app->params['uploadPath'];
        
        $file = new \yii\helpers\FileHelper();
       
        $file->createDirectory(Yii::$app->basePath.'/..'.$targetFolder);
        
        
        if (!empty($_FILES)) {

            $tempFile = $_FILES['file']['tmp_name'];
            $fileParts = pathinfo($_FILES['file']['name']);
            $extension = $fileParts['extension'];
            $random = time() . rand(1000, 9999);
            $fileName = Yii::$app->request->post("fname") . "." . $extension;


            $targetFile = rtrim(Yii::$app->basePath.'/../'.$targetFolder, '/') . '/' . $fileName;
            $fileTypes = array('jpg', 'jpeg', 'gif', 'png');
            
            $uploadfile_path = $targetFolder . '/' . $fileName;

            if (file_exists($targetFile)) {
                unlink($targetFile);
            }

            $callback['url'] = $uploadfile_path;
            $callback['filename'] = $fileParts['filename'];
            $callback['randName'] = $random;


            if (in_array($fileParts['extension'], $fileTypes)) {
                move_uploaded_file($tempFile, $targetFile);
                echo json_encode($callback);
            } else {
                echo '不能上传后缀为' . $fileParts['extension'] . '文件';
            }
        } else {
            echo "没有上传文件";
        }
    }

}
